﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WikiQuizz.Common.Interfaces;
using System.Xml.Linq;
using WikiQuizz.Common.Resource;

namespace WikiQuizz.StandardImplementations
{
    public class PopulationDensityFilter : IPopulationDensityFilter
    {
        public string Filter(IEnumerable<XNode> rawData)
        {
            string res = ExtractCandidateNode(rawData);

            if (!res.Contains(Strings.POPOLATION_DENSITY_IDENTIFYER))
            {
                res = String.Format("{0} {1}", res.Trim(), Strings.POPOLATION_DENSITY_IDENTIFYER);
            }

            return res;
        }

        private static string ExtractCandidateNode(IEnumerable<XNode> rawData)
        {
            var withoutSmall = (from o in rawData
                                where !o.ToString().Contains("<small")
                                select o);

            var withoutSup = (from o in withoutSmall
                              where !o.ToString().StartsWith("<sup")
                              select o);

            var withoutHRef = (from o in withoutSup
                               where !o.ToString().StartsWith("<a href")
                               select o);

            var withoutBr = (from o in withoutHRef
                             where !o.ToString().StartsWith("<br")
                             select o);

            var withoutAngleBrackets = (from o in withoutBr
                                        where !o.ToString().StartsWith("[")
                                        select o);

            var withoutBrackets = (from o in withoutAngleBrackets
                                   where !(o.ToString().StartsWith("(") && o.ToString().EndsWith(")"))
                                   select o);

            var withoutOnlyCloseBracket = (from o in withoutBrackets
                                           where !o.ToString().Equals(")")
                                           select o);

            var withoutOnlyOpenBracket = (from o in withoutOnlyCloseBracket
                                          where !o.ToString().Equals("(")
                                          select o);

            return withoutOnlyOpenBracket.FirstOrDefault().ToString();
        }
    }
}
